package com.codeczx.customviewdemo;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by win10 on 2017/6/27.
 */

public class EasyLinearLayout extends ViewGroup {

    private static final String TAG = "EasyLinearLayout";

    public EasyLinearLayout(Context context) {
        super(context);
    }

    public EasyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EasyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        int layoutWidth = 0;
        int layoutHeight = 0;
        int maxChildHeight = 0;
        for (int i = 0; i < count; i++) {
            Log.i(TAG, "onLayout: i=" + i);
            View view = getChildAt(i);
            int childMeasureWidth = view.getMeasuredWidth();
            int childMeasureHeight = view.getMeasuredHeight();
            Log.i(TAG, "onLayout: getWidth():" + getWidth());
            if (layoutWidth + childMeasureWidth < getWidth()) {
                l = layoutWidth;
                r = l + childMeasureWidth;
                t = layoutHeight;
                b = t + childMeasureHeight;
            } else {
                layoutWidth = 0;
                l = layoutWidth;
                r = l + childMeasureWidth;
                layoutHeight += maxChildHeight;
                maxChildHeight = 0;
                t = layoutHeight;
                b = t + childMeasureHeight;
            }

            layoutWidth += childMeasureWidth;
            if (childMeasureHeight > maxChildHeight) {
                maxChildHeight = childMeasureHeight;
            }

            view.layout(l, t, r, b);
            Log.i(TAG, "onLayout: " + l + " " + t + " " + r + " " + b + " ");
        }
    }
}
